from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
from sqlalchemy.orm import Session
from database import get_db
from models import User, SystemConfig
from schemas import SystemConfigResponse, SystemConfigUpdate
from utils.auth_utils import get_current_user
from logger import logging
import os
import shutil
from datetime import datetime

router = APIRouter(prefix="/api/admin/config", tags=["配置管理"])

# 确保上传目录存在
UPLOAD_DIRS = {
    "floor_guide": "uploads/images/floor_guide",
    "videos": "uploads/videos"
}

for dir_path in UPLOAD_DIRS.values():
    os.makedirs(dir_path, exist_ok=True)


@router.get("", response_model=SystemConfigResponse, summary="获取系统配置")
async def get_system_config(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取系统配置信息

    需要登录后访问
    """
    try:
        # 查询配置，如果不存在则创建默认配置
        config = db.query(SystemConfig).first()

        if not config:
            config = SystemConfig(
                avatar_prompt="",
                internal_knowledge_id="",
                internal_knowledge_api_key="",
                external_knowledge_id="",
                external_knowledge_api_key="",
                ai_model_api_url="",
                ai_model_name="",
                ai_model_api_key="",
                voice_config="",
                floor_guide_image="",
                video_resources=[]
            )
            db.add(config)
            db.commit()
            db.refresh(config)

        logging.info(f"用户 {current_user.username} 查询系统配置")

        return config
    except Exception as e:
        logging.error(f"获取系统配置失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取系统配置失败"
        )


@router.put("", response_model=SystemConfigResponse, summary="更新系统配置")
async def update_system_config(
    config_update: SystemConfigUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    更新系统配置信息

    所有字段都是可选的，只更新提供的字段

    - **avatar_prompt**: 数字人提示词配置
    - **internal_knowledge_id**: 内部知识库ID
    - **internal_knowledge_api_key**: 内部知识库API密钥
    - **external_knowledge_id**: 外部知识库ID
    - **external_knowledge_api_key**: 外部知识库API密钥
    - **ai_model_api_url**: AI模型API地址
    - **ai_model_name**: AI模型名称
    - **ai_model_api_key**: AI模型API密钥
    - **voice_config**: 音色配置
    - **floor_guide_image**: 楼层导览图片路径
    - **video_resources**: 视频资源配置列表
    """
    try:
        # 查询配置
        config = db.query(SystemConfig).first()

        if not config:
            # 如果配置不存在，创建新配置
            config = SystemConfig()
            db.add(config)

        # 更新字段
        update_data = config_update.model_dump(exclude_unset=True)

        # 处理视频资源（转换为JSON格式）
        if "video_resources" in update_data and update_data["video_resources"] is not None:
            update_data["video_resources"] = [
                video.model_dump() if hasattr(video, 'model_dump') else video
                for video in update_data["video_resources"]
            ]

        for field, value in update_data.items():
            setattr(config, field, value)

        # 提交更改
        db.commit()
        db.refresh(config)

        logging.info(f"用户 {current_user.username} 更新了系统配置")

        return config
    except Exception as e:
        db.rollback()
        logging.error(f"更新系统配置失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新系统配置失败: {str(e)}"
        )


@router.post("/upload/floor-guide", summary="上传楼层导览图片")
async def upload_floor_guide_image(
    file: UploadFile = File(...),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    上传楼层导览图片

    - **file**: 图片文件（支持 JPG、PNG、GIF）

    返回图片的访问路径
    """
    try:
        # 验证文件类型
        allowed_types = ["image/jpeg", "image/png", "image/gif"]
        if file.content_type not in allowed_types:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="只支持 JPG、PNG、GIF 格式的图片"
            )

        # 验证文件大小 (最大5MB)
        file_content = await file.read()
        if len(file_content) > 5 * 1024 * 1024:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="图片大小不能超过5MB"
            )

        # 生成文件名
        file_extension = os.path.splitext(file.filename)[1]
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        new_filename = f"floor_guide_{timestamp}{file_extension}"
        file_path = os.path.join(UPLOAD_DIRS["floor_guide"], new_filename)

        # 保存文件
        with open(file_path, "wb") as buffer:
            buffer.write(file_content)

        # 生成访问URL
        file_url = f"/api/uploads/images/floor_guide/{new_filename}"

        logging.info(f"用户 {current_user.username} 上传了楼层导览图片: {new_filename}")

        return {
            "message": "图片上传成功",
            "url": file_url,
            "filename": new_filename
        }
    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"上传楼层导览图片失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"上传图片失败: {str(e)}"
        )


@router.post("/upload/video", summary="上传视频文件")
async def upload_video(
    file: UploadFile = File(...),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    上传视频文件

    - **file**: 视频文件（支持 MP4、AVI、MOV）

    返回视频的访问路径
    """
    try:
        # 验证文件类型
        allowed_types = ["video/mp4", "video/avi",
                         "video/quicktime", "video/x-msvideo"]
        if file.content_type not in allowed_types:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="只支持 MP4、AVI、MOV 格式的视频"
            )

        # 生成文件名
        file_extension = os.path.splitext(file.filename)[1]
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        new_filename = f"video_{timestamp}{file_extension}"
        file_path = os.path.join(UPLOAD_DIRS["videos"], new_filename)

        # 保存文件（流式保存，避免内存溢出）
        with open(file_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # 生成访问URL
        file_url = f"/api/uploads/videos/{new_filename}"

        logging.info(f"用户 {current_user.username} 上传了视频文件: {new_filename}")

        return {
            "message": "视频上传成功",
            "url": file_url,
            "filename": new_filename
        }
    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"上传视频文件失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"上传视频失败: {str(e)}"
        )


@router.post("/reset", summary="重置系统配置")
async def reset_system_config(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    重置系统配置为默认值

    将清空所有配置项
    """
    try:
        config = db.query(SystemConfig).first()

        if config:
            # 重置所有字段
            config.avatar_prompt = ""
            config.internal_knowledge_id = ""
            config.internal_knowledge_api_key = ""
            config.external_knowledge_id = ""
            config.external_knowledge_api_key = ""
            config.ai_model_api_url = ""
            config.ai_model_name = ""
            config.ai_model_api_key = ""
            config.voice_config = ""
            config.floor_guide_image = ""
            config.video_resources = []

            db.commit()
            db.refresh(config)

        logging.info(f"用户 {current_user.username} 重置了系统配置")

        return {"message": "系统配置已重置"}
    except Exception as e:
        db.rollback()
        logging.error(f"重置系统配置失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="重置系统配置失败"
        )
